import router from './router';
import store from './store';
import NProgress from 'nprogress'; // progress bar
import 'nprogress/nprogress.css'; // progress bar style
import { isLogin } from '@/utils/auth'; // getToken from cookie

NProgress.configure({ showSpinner: false }); // NProgress Configuration

const whiteList = ['/login', '/authredirect']; // no redirect whitelist

// 根据菜单区分权限
function permissionWithMenus(to, next) {
  if (store.getters.adminMenus.length === 0 && !store.getters.menusLoaded) {
    store.dispatch(types.GET_ADMIN_LIST_MENU).then(({ result, data }) => {
      // 拉取菜单列表
      store.dispatch('GenerateRoutesWithMenus', data).then(() => {
        // 根据菜单生成路由
        router.addRoutes(store.getters.addRouters); // 动态添加可访问路由表
        next({ ...to, replace: true }); // hack方法 确保addRoutes已完成 ,set the replace: true so the navigation will not leave a history record
      });
    });
  } else {
    // 没有动态改变权限的需求可直接next() 删除下方权限判断 ↓
    // if (hasPermissionMenus(store.getters.permissionRouters, to.name)) {
    if (to.path === '/') {
      // 目前没有首页，所以目标路由为根路由时，显示用户的第一个路由
      const firstMenuGroup = store.getters.addRouters[0];
      let firstMenu = {};
      let firstRoute = '';
      if (
        firstMenuGroup &&
        firstMenuGroup.children &&
        firstMenuGroup.children[0]
      ) {
        firstMenu = firstMenuGroup.children[0];
        firstRoute = `${firstMenuGroup.path}/${firstMenu.path}`;
      } else {
        const findMenuGroup = _.find(
          store.getters.addRouters,
          item => item && item.children && item.children[0]
        );
        // 仅考虑一级主目录不选择菜单的情况
        firstMenu = findMenuGroup.children[0];
        firstRoute = `${findMenuGroup.path}/${firstMenu.path}`;
      }
      next(firstRoute);
    } else {
      next(); //
    }
    // } else {
    //   next({ path: '/401', replace: true, query: { noGoBack: true }})
    // }
  }
}

// 没有网络时使用本地菜单
function permissionWithMenusWithoutNet(to, next) {
  if (store.getters.adminMenus.length === 0 && !store.getters.menusLoaded) {
    store.dispatch('GenerateRoutesWithMenusWithoutNet', {}).then(() => {
      // 根据菜单生成路由
      router.addRoutes(store.getters.addRouters); // 动态添加可访问路由表
      next({ ...to, replace: true }); // hack方法 确保addRoutes已完成 ,set the replace: true so the navigation will not leave a history record
    });
  } else {
    // 没有动态改变权限的需求可直接next() 删除下方权限判断 ↓
    // if (hasPermissionMenus(store.getters.permissionRouters, to.name)) {
    next(); //
    // } else {
    //   next({ path: '/401', replace: true, query: { noGoBack: true }})
    // }
  }
}

router.beforeEach((to, from, next) => {
  // 如果是刷新  则重定向到原路由
  if (store.getters.visitedViews.length <= 1 && to.query.index > 1) {
    router.push({
      path: to.path
    });
  }
  NProgress.start(); // start progress bar
  if (process.env.NODE_ENV === 'development') {
    // 没有网络时调用
    // permissionWithMenusWithoutNet(to, next);
  }
  // 有网络时调用
  if (isLogin()) {
    // determine if there has token
    /* has token */
    if (to.path === '/login') {
      next({ path: '/' });
      NProgress.done(); // if current page is dashboard will not trigger	afterEach hook, so manually handle it
    } else {
      permissionWithMenus(to, next);
      // permissionWithRoles(to, next)
      // 数据权限
      store.dispatch('getDataPermissionList');
    }
  } else {
    /* has no token */
    if (whiteList.indexOf(to.path) !== -1) {
      // 在免登录白名单，直接进入
      next();
    } else {
      next('/login'); // 否则全部重定向到登录页
      NProgress.done(); // if current page is login will not trigger afterEach hook, so manually handle it
    }
  }
});

router.afterEach((to, from) => {
  NProgress.done(); // finish progress bar
  if (to.path.includes(from.path)) return;
  if (isLogin()) {
    const content = _.getContent(to);
    if (content !== '') {
      store.dispatch(types.SAVE_OPERATION_LOG, { content });
    }
  }
});
